<template>
  <div class="upload-form">
    <el-form :model="form" :rules="rules" ref="form">
      <el-form-item label="作品标题" :label-width="formLabelWidth" prop="title">
        <el-input v-model="form.title" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="作品简介" :label-width="formLabelWidth" prop="intro">
        <el-input type="textarea" v-model="form.intro" rows="4"></el-input>
      </el-form-item>
      <el-form-item label="创意主图" :label-width="formLabelWidth" prop="mainPic" >
        <el-upload
          id="mainPic"
          action=""
          ref="mainPic"
          list-type="picture-card"
          :auto-upload="false"
          :multiple="false"
          :limit="1"
          accept="image/*"
          :class="{'hide':mainPicUrl.length !== 0}"
          class="input-item"
          :on-change="mainPicChange"
          :on-remove="mainPicRemove"
          >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="* 创意图集" :label-width="formLabelWidth" prop="pics" >
        <el-upload
          id="pics"
          ref="pics"
          action=""
          list-type="picture-card"
          :auto-upload="false"
          :multiple="true"
          :limit="10"
          accept="image/*"
          :class="{'hide':picsUrl.length >= 4}"
          :on-change="picsChange"
          :on-remove="picsRemove"
          :on-exceed="exceedLimit"
          style="height:96px">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer xui-text-center" >
      <el-button type="primary" v-loading="loading" :disabled="disable" @click="validateAndSubmit">确 定</el-button>
    </div>
  </div>
</template>
<script>
import { childrenEle } from "@/utils";
import { getToken } from "@/utils/auth.js";
import { rootsUrl } from "@/utils";
export default {
  props: ["id"],
  data() {
    return {
      files: [],
      formLabelWidth: "120px",
      form: {
        title: "",
        intro: "",
        mainPic: null,
        pics: []
      },
      mainPicUrl: "",
      picsUrl: [],
      rules: {
        title: [{ required: true, message: "请输入作品标题", trigger: "blur" }],
        intro: [{ required: true, message: "请输入作品简介", trigger: "blur" }],
        mainPic: [{ required: true, message: "请上传主图", trigger: "change" }]
      },
      loading: false,
      disable: false
    };
  },
  computed: {
    userId() {
      return this.$store.getters.userId;
    },
    userName() {
      return this.$store.getters.userName;
    },
    uploadUrl() {
      return `${rootsUrl[3]}/cbculture/design/saveDesign.shtml`;
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    mainPicChange(file) {
      if (!file) {
        return false;
      }
      if (this.picCondition(file)) {
        this.mainPicUrl = file.url;
        this.form.mainPic = file.url;
      } else {
        this.$refs.mainPic.clearFiles();
      }
    },
    mainPicRemove(file) {
      if (!file) {
        return false;
      }
      if (this.mainPicUrl == file.url) {
        this.mainPicUrl = "";
        this.form.mainPic = "";
        this.$refs.mainPic.clearFiles();
      }
    },
    picsChange(file, fileList) {
      this.picsUrl.push(file.url);
      this.files.push(file.raw);
    },
    picsRemove(file) {
      if (!file) {
        return false;
      }
      let index = this.picsUrl.indexOf(file.url);
      if (index > -1) {
        this.picsUrl.splice(index, 1);
      }
      this.files.splice(this.files.indexOf(file.raw), 1);
    },
    picCondition(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    submitArt() {
      // loading状态
      this.loading = true;
      this.disable = true;
      // 新建formdata对象
      let data = new FormData();
      // 将数据手动添加到formData对象中
      data.append("aid", this.id);
      data.append("uid", this.userId);
      data.append("uname", this.userName);
      data.append("title", this.form.title);
      data.append("content", this.form.intro);
      let token = getToken();
      data.append("token", token);
      let mainPic = document.getElementById("mainPic").children[1].children[1]
        .files;
      let pics = this.files;
      data.append("picture", mainPic[0]); //通过append向form对象添加数据
      for (let i = 0; i < pics.length; i++) {
        data.append("pictures", pics[i]);
      }
      // 设置请求头格式
      let config = {
        headers: { "Content-Type": "multipart/form-data" }
      };
      // 通过post方式提交数据。
      this.$axios
        .post(this.uploadUrl, data, config)
        .then(res => {
          this.loading = false;
          this.disable = false;
          if (res.data.flag != 1) {
            this.$message({
              showClose: true,
              type: "error",
              message: res.data.msg
            });
            return false;
          }
          this.$message({
            showClose: true,
            type: "success",
            message: res.data.msg + "审批通过后显示出来。"
          });
          this.$emit("done");
          this.$refs.form.resetFields();
          this.$refs.mainPic.clearFiles();
          this.$refs.pics.clearFiles();
          this.mainPicUrl = "";
          this.picsUrl = [];
        })
        .catch(err => {
          this.loading = false;
          this.disable = false;
        });
    },
    validateAndSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.picsUrl < 1) {
            this.$message({
              showClose: true,
              type: "error",
              message: "请选择图集的图片后再上传。"
            });
            return false;
          }
          this.submitArt();
        } else {
          this.$message({
            showClose: true,
            type: "error",
            message: "请填写相关信息后再上传。"
          });
        }
      });
    },
    exceedLimit() {
      this.$message({
        type: "warning",
        message: "最多上传4张创意图集"
      });
    }
  },
  mounted() {
    this.mainPicUrl = "";
    this.form.pics = "";
    this.$refs.pics.clearFiles();
  }
};
</script>

<style lang="less">
.upload-form .input-item.hide {
  // height: 96px;
  .el-upload--picture-card {
    display: none !important;
  }
  position: relative;
}
.upload-form #pics.hide {
  .el-upload--picture-card {
    display: none !important;
  }
}
.el-button--primary {
  color: #fff;
  background-color: #dbad23;
  border-color: #dbad23;
}
</style>

